<template>
  <q-layout view="lHh Lpr lFf">
    <q-page-container>
      <!-- 路由出口 - 关键的keep-alive实现 -->
      <router-view v-slot="{ Component, route }">
        <keep-alive :include="cachedViews">
          <component 
            :is="Component" 
            v-if="route.meta && route.meta.keepAlive"
            :key="route.name" 
          />
        </keep-alive>
        <component 
          :is="Component" 
          v-if="!route.meta || !route.meta.keepAlive"
          :key="route.fullPath" 
        />
      </router-view>
    </q-page-container>

    <!-- 底部TabBar -->
    <q-footer v-show="isTabPage" :style="footerStyle">
      <q-tabs
        v-model="activeTab"
        :dense="false"
        class="text-white shadow-2"
        @update:model-value="switchTab"
      >
        <!-- <q-tab name="home" label="首页" />
        <q-tab name="category" label="分类" /> -->
        <q-tab name="square" label="广场">
          
        </q-tab>
        <q-tab name="message" label="消息" >
          <q-badge color="red" floating rounded></q-badge>
        </q-tab>
        <q-tab name="profile" label="我的" />
      </q-tabs>
    </q-footer>
  </q-layout>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { setTransColor } from 'src/utils/common'
const route = useRoute()
const router = useRouter()

// Tab相关状态
const activeTab = ref('home')

// 缓存的视图组件名称 - 这里很关键
const cachedViews = ref(['HomePage', 'CategoryPage', 'SquarePage', 'ProfilePage','MessagePage'])

// 是否是Tab页面
const isTabPage = computed(() => {
  return route.meta && route.meta.isTab === true
})

// Tab路由映射
const tabRouteMap = {
  'home': '/home',
  'category': '/category', 
  'square': '/square',
  'profile': '/profile',
  'message': '/message'
}

// 反向映射
const pathToTabMap = {
  '/home': 'home',
  '/category': 'category',
  '/square': 'square', 
  '/profile': 'profile',
  '/message': 'message'
}

// 切换Tab
const switchTab = (tabName) => {
  const targetPath = tabRouteMap[tabName]
  if (targetPath && targetPath !== route.path) {
    console.log('切换Tab:', tabName, targetPath)
    router.push(targetPath)
  }
}

const footerStyle = ref()
// 监听路由变化，更新活跃Tab
watch(() => route.path, (newPath) => {
  const tabName = pathToTabMap[newPath]
  if (tabName) {
    activeTab.value = tabName
  }
  footerStyle.value = setTransColor()
}, { immediate: true })

onMounted(() => {
  console.log('MainLayout mounted')
})
</script>

<style scoped>

</style>